import { notFound } from 'next/navigation'
import { existsSync } from 'fs'
import { join } from 'path'
import { getTools } from '@/lib/database'
import { ReviewList } from '@/components/reviews/review-list'
import { ReviewForm } from '@/components/reviews/review-form'
import { FavoriteButton } from '@/components/favorites/favorite-button'

// 添加全局样式来防止滚动条
const globalStyles = `
  html, body {
    overflow: hidden !important;
    height: 100% !important;
    width: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
  }

  * {
    box-sizing: border-box;
  }

  iframe {
    display: block !important;
    border: none !important;
    outline: none !important;
  }
`

interface ToolPageProps {
  params: Promise<{
    id: string
  }>
  searchParams: Promise<{
    minimal?: string
    pure?: string
  }>
}

export default async function DeployedToolPage({ params, searchParams }: ToolPageProps) {
  const { id } = await params
  const { minimal, pure } = await searchParams

  // 检查工具是否存在
  const toolPath = join(process.cwd(), 'public', 'deployed-tools', id, 'index.html')

  if (!existsSync(toolPath)) {
    notFound()
  }

  // 获取工具信息
  const tools = await getTools()
  const tool = tools.find(t => t.id === id)

  // 检查显示模式
  const isMinimal = minimal === 'true'
  const isPure = pure === 'true'

  if (isPure) {
    // 纯净模式：完全无装饰，只有工具
    return (
      <>
        <style dangerouslySetInnerHTML={{ __html: globalStyles }} />
        <div className="fixed inset-0 w-full h-full overflow-hidden">
          <iframe
            src={`/deployed-tools/${id}/index.html`}
            className="w-full h-full border-0 block"
            title={tool?.title || '部署的工具'}
            sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"
          />
        </div>
      </>
    )
  }

  if (isMinimal) {
    // 极简模式：只显示工具，带浮动控制按钮
    return (
      <>
        <style dangerouslySetInnerHTML={{ __html: globalStyles }} />
        <div className="fixed inset-0 w-full h-full bg-white overflow-hidden">
          <iframe
            src={`/deployed-tools/${id}/index.html`}
            className="w-full h-full border-0 block"
            title={tool?.title || '部署的工具'}
            sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"
          />

        {/* 浮动控制按钮 */}
        <div className="fixed top-4 right-4 z-50 flex gap-2">
          <a
            href={`/tools/deployed/${id}?pure=true`}
            className="inline-flex items-center px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm text-xs font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            title="纯净模式（无任何装饰）"
          >
            ✨ 纯净
          </a>
          <a
            href={`/tools/deployed/${id}`}
            className="inline-flex items-center px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm text-xs font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            title="显示完整页面"
          >
            📋 完整
          </a>
          <a
            href="/"
            className="inline-flex items-center px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm text-xs font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            title="返回首页"
          >
            🏠 首页
          </a>
        </div>
        </div>
      </>
    )
  }

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: globalStyles }} />
      <div className="fixed inset-0 w-full h-full bg-white overflow-hidden flex flex-col">
      {/* 顶部工具栏 - 紧凑设计 */}
      <div className="bg-gray-50 border-b border-gray-200 px-4 py-2 flex-shrink-0">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            {tool && (
              <>
                <h1 className="text-lg font-semibold text-gray-900">{tool.title}</h1>
                <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
                  {tool.category.icon} {tool.category.name}
                </span>
              </>
            )}
          </div>

          <div className="flex items-center space-x-2">
            <FavoriteButton
              toolId={id}
              size="sm"
              variant="ghost"
              showText={false}
            />
            <a
              href={`/tools/deployed/${id}?pure=true`}
              className="inline-flex items-center px-3 py-1 text-xs font-medium text-purple-600 hover:text-purple-700"
              title="纯净模式（无任何装饰）"
            >
              ✨ 纯净
            </a>
            <a
              href={`/tools/deployed/${id}?minimal=true`}
              className="inline-flex items-center px-3 py-1 text-xs font-medium text-green-600 hover:text-green-700"
              title="极简模式"
            >
              🎯 极简
            </a>
            <a
              href={`/deployed-tools/${id}/index.html`}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center px-3 py-1 text-xs font-medium text-blue-600 hover:text-blue-700"
              title="在新窗口中打开"
            >
              ↗ 新窗口
            </a>
            <a
              href="/"
              className="inline-flex items-center px-3 py-1 text-xs font-medium text-gray-600 hover:text-gray-700"
              title="返回首页"
            >
              ← 首页
            </a>
          </div>
        </div>
      </div>

      {/* 工具iframe容器 - 占据剩余全部空间 */}
      <div className="flex-1 overflow-hidden">
        <iframe
          src={`/deployed-tools/${id}/index.html`}
          className="w-full h-full border-0 block"
          title={tool?.title || '部署的工具'}
          sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"
        />
      </div>
      </div>
    </>
  )
}

// 强制动态渲染，因为页面使用了 searchParams
export const dynamic = 'force-dynamic'

// 生成静态参数（可选，用于构建时优化）
export async function generateStaticParams() {
  return []
}
